package com.xcity.game.combat;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

import com.xcity.game.combat.buff.CombatBuff;
import com.xcity.game.combat.listener.action.ActionAdapter;
import com.xcity.game.combat.unit.CombatUnit;

/**
 * 一个战斗回合
 * @author yang.li
 *
 */
public class Round {

	protected Combat ref;
	protected int round; // 回合索引(0~)
	protected List<Action> actions;
	protected List<CombatBuff> buffs; // 回合结束后需要处理的buff
	protected int actionIndex;
	
	public Round(Combat ref, int round) {
		this.ref = ref;
		this.round = round;
		this.actions = new ArrayList<Action>();
	}
	
	public void add(Action action) {
		action.index = actions.size();
		action.ref = this;
		actions.add(action);
	}
	
//	public Round next() {
//		return new Round(++round);
//	}

	public int getRound() {
		return round;
	}

	public List<Action> getActions() {
		if (actionIndex > 0 && actionIndex < actions.size()) {
			return actions.subList(actionIndex, actions.size());
		}
		return actions;
	}
	
	public List<CombatBuff> getBuffs() {
		return buffs != null ? buffs : Collections.emptyList();
	}
	
	public void addBuff(CombatBuff buff) {
		if (buff.getTemplate() != null) {
			if (buffs == null)
				buffs = new ArrayList<CombatBuff>();
			buffs.add(buff);
		}
	}

	public synchronized void useSkill(Combat combat, int actionIndex) {
		this.actionIndex = actionIndex;
		Deque<CombatUnit> deque = new LinkedList<CombatUnit>();
		for (int i = actions.size() - 1; i >= actionIndex; i--) {
			Action action = actions.remove(i);
			action.rollback(combat);
			deque.offerFirst(action.unit);
		}
		if (combat.isEnd()) {
			combat.state = Combat.State.COMBATING; // rollback state
		}
		combat.roundCalc(this, deque, new ActionAdapter() {
			@Override
			public void preAction(Action action) {
				if (action.index == actionIndex) {
					action.useSkill = true;
				}
			}
		});
		
	}
	
	public Combat ref() {
		return ref;
	}
	
	public List<Action> actionList() {
		return actions;
	}
	
}
